/**
 * 
 * Sun CMS
 * 
 * @author			Burning
 * @copyright		Copyright (c) 2009, IsunCms.Com.
 * @license			http://www.isuncms.com/license.htm
 * @link				http://www.isuncms.com/
 * @since				Version 1.0 Beta
 * 
 */

 $(function(){
	$.ajaxSetup({dataType:'json', type: "POST"});
	$(":text,:password,:file,select,textarea").mouseover(function(){$(this).css('border','1px solid #00CCFF');}).mouseout(function(){$(this).css('border','1px solid #6688AA');}).focus(function(){$(this).css('border','1px solid #FF8800');});
	$(".top_menu li").mouseover(function(){$(this).addClass("mover")}).mouseout(function(){$(this).removeClass("mover");});
	$(".left_menu ul li").click(function(){$(".left_menu ul li").removeClass("active");$(this).addClass("active")});
	$("#left_menu ul li").mouseover(function(){$(this).addClass("hover")}).mouseout(function(){$(this).removeClass("hover");});
});

var dialog = {
	iframeNo: 0,
	xy: function (e,v){return (v?($.browser.msie?event.clientY+document.body.scrollTop:e.pageY):($.browser.msie?event.clientX+document.body.scrollTop:e.pageX)); },
	drag: function (d,e)
	{
		var oX=parseInt(d.style.left),oY=parseInt(d.style.top),eX=this.xy(e),eY=this.xy(e,1),tX,tY,stop;
		document.onmousemove=function(e){if(!stop){ d.style.top=(tX=dialog.xy(e,1)+oY-eY+'px'); d.style.left=(tY=dialog.xy(e)+oX-eX+'px'); }};
		document.onmouseup=function(){stop=1; document.onmousemove=''; document.onmouseup='';};
	},
	open: function (id, name, str, button, align, width, height)
	{
		var x = (document.body.scrollWidth-width)*0.5;
		var y = (document.body.scrollHeight-height)*0.5;
		var zIndex=0;
		if((this.iframeNo==0)&&(id!=0)){this.dialogBg('open');zIndex=901;this.iframeNo=1;}
		else if((this.iframeNo>0)&&(id>this.iframeNo)){var n=901+this.iframeNo;$("#_dialogbg").css('z-index',n);this.iframeNo=this.iframeNo+1;zIndex=900+this.iframeNo;}
		else{this.alertBg('open');zIndex=999;}
		var dialog_id = id==0?'dialog_alert':'dialog_'+id;
		var close = id==0?'alertClose();':'dialogClose('+id+');';
		var html = '<div style="position: absolute; display: block; z-index: '+zIndex+'; left: '+x+'px; top: '+y+'px;width:'+(width+26)+'px;" onmousedown="dialog.drag(this,event)" id="'+dialog_id+'"><table cellspacing="0" cellpadding="0" border="0"><tbody><tr style="cursor: move;"><td height="33" width="13" style="background-image: url(images/system/dialog/dialog_lt.png) ! important;"><div style="width: 13px;"></div></td><td height="33" style="background-image: url(images/system/dialog/dialog_ct.png) ! important;"><div style="padding: 9px 0pt 0pt 4px; float: left; font-weight: bold; color: rgb(255, 255, 255);"><img align="absmiddle" src="images/system/dialog/icon_dialog.gif"/> '+name+' </div><div onclick="dialog.'+close+'"  onmouseout="this.style.backgroundImage=\'url(images/system/dialog/dialog_closebtn.gif)\'" onmouseover="this.style.backgroundImage=\'url(images/system/dialog/dialog_closebtn_over.gif)\'" style="margin: 5px 0pt 0pt; position: relative; cursor: pointer; float: right; height: 17px; width: 28px; background-image: url(images/system/dialog/dialog_closebtn.gif);"></div></td><td height="33" width="13" style="background-image: url(images/system/dialog/dialog_rt.png) ! important;"><div style="width: 13px;"></div></td></tr><tr><td width="13" style="background-image: url(images/system/dialog/dialog_mlm.png) ! important;"></td><td align="center" valign="top" style="background:#ffffff;"><div style="overflow: visible;height:'+(height+37)+'px;width:'+width+'px" scrolling="auto" ><table height="100%" id="dialog_content" cellspacing="0" cellpadding="10" border="0"><tbody><tr align="left" valign="top"><td>'+str+'</td></tr><tr height="36px"><td><div style="border-top: 1px solid rgb(218, 222, 229); padding: 8px 20px; text-align: '+align+'; background-color: rgb(246, 246, 246);">'+button+'</div></td></tr></tbody></table></div></td><td width="13" style="background-image: url(images/system/dialog/dialog_mrm.png) ! important;"/></tr><tr><td height="13" width="13" style="background-image: url(images/system/dialog/dialog_lb.png) ! important;"/><td style="background-image: url(images/system/dialog/dialog_cb.png) ! important;"/><td height="13" width="13" style="background-image: url(images/system/dialog/dialog_rb.png) ! important;"/></tr></tbody></table></div>';
		$("#dialog").append(html);
	},
	dialogClose: function (id){$("#dialog #dialog_"+id).fadeOut().remove();if(this.iframeNo==1){this.dialogBg('close');this.iframeNo=0;}else{this.iframeNo=this.iframeNo-1;var n=899+this.iframeNo;$("#_dialogbg").css('z-index',n);}},
	alertClose: function (){$("#dialog #dialog_alert").fadeOut().remove();this.alertBg('close');},
	dialogBg: function (action){action == 'open'?$("#dialog #_dialogbg").fadeIn():$("#dialog #_dialogbg").fadeOut();},
	alertBg: function (action){action == 'open'?$("#dialog #_alertbg").show():$("#dialog #_alertbg").hide();},
	alert: function (msg,closeDialogId)
	{
		var onclick = (typeof closeDialogId == "undefined")?'dialog.alertClose();':'dialog.alertClose();dialog.dialogClose('+closeDialogId+');';
		var html = '<table height="100%" cellspacing="0" cellpadding="10" border="0"><tbody><tr valign="center"><td style="padding:0 20px;text-align:center;"><img height="34" width="34"  src="images/system/icon_alert.gif" /></td><td style="padding-right:20px;text-align:left;"><div id="msg">'+msg+'</div></td></tr></tbody></table>';
		var button = '<a class="slbutton" href="javascript:void(1);" onclick="'+onclick+'"><input type="button" class="srbutton" value="确 定"/></a>';
		this.open(0,'系统提示',html,button,'center',300, 150);
	},
	query: function (msg,func)
	{
		var html = '<table height="100%" cellspacing="0" cellpadding="10" border="0"><tbody><tr valign="center"><td style="padding:0 20px;text-align:center;"><img height="34" width="34"  src="images/system/icon_query.gif" /></td><td style="padding-right:20px;text-align:left;"><div id="msg">'+msg+'</div></td></tr></tbody></table>';
		var button = '<a class="slbutton" href="javascript:void(1);" onclick="'+func+';dialog.alertClose();"><input type="button" class="srbutton" value="确 定"/></a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="slbutton" href="javascript:void(1);"><input type="button" class="srbutton" onclick="dialog.alertClose();" value="取 消"/></a>';
		this.open(0,'信息确认',html,button,'center',300, 150);
	},
	iframe: function(id,name,url,yesButton,noButton,width,height)
	{
		var buttonLeft = '<a class="slbutton" href="javascript:void(1);">';
		var buttonRight = '</a>';
		var yesButtonHtml = '';
		if(yesButton==1){yesButtonHtml='<input type="button" class="srbutton" onclick="window.frames['+id+'].document.getElementById(\'sbt\').click();" value="确 定"/>';}
		else if(yesButton==2){yesButtonHtml='<input type="button" class="srbutton" onclick="dialog.dialogClose('+id+');" value="确 定"/>';}
		var noButtonHtml = '<input type="button" class="srbutton" onclick="dialog.dialogClose('+id+');" value="取 消"/>'
		var button = (yesButtonHtml!=''?buttonLeft+yesButtonHtml+buttonRight:'')+((yesButton!=2&&noButton)?'&nbsp;&nbsp;&nbsp;&nbsp;'+buttonLeft+noButtonHtml+buttonRight:'');
		var html = '<iframe id="dialog_iframe_'+id+'" scrolling="auto" style="width:'+width+'px;height:'+height+';" frameborder="0" src="'+SITE_URL+SCRIPT+url+'"></iframe>';
		this.open(id,name,html,button,'right',width,height);
	}
}

var global = {
	tabId: 1,
	childArray: [],
	open: function(str){$("#s_"+str).show();},
	close: function(str){$("#s_"+str).hide();},
	insert: function(str){$("#"+str[0]).val(str[1]);sclose(str[0])},
	checkAll: function()
	{
		/** todo: 全选/反选 **/
		var flag = ($("#checkbox").attr("checked")==true)?true:false;
		$(".checkbox").each(function(){
			flag?$(this).attr("checked", 'true'):$(this).removeAttr("checked");
			flag?$(this).parent().parent().addClass('tr_selected'):$(this).parent().parent().removeClass("tr_selected");
		});
	},
	getChecked: function()
	{
		/** todo: 获取选中的checkbox **/
		var checked = new Array();
		$(".checkbox").each(function(){
			if($(this).attr('checked')==true){
				checked.push($(this).val());
			}
		});
		return checked;
	},
	radioValue: function(name)
	{
		/** todo: 获取选中的radio的值 **/
		var value = '';
		$(":radio").each(function(){
			if($(this).attr('name')==name && $(this).attr('checked')==true){
				value = $(this).val();
			}
		});
		return value;
	},
	editorDialog: function(w,h)
	{
		/** todo: 改变编辑器dialog宽高 **/
		$(".ke-dialog").css({"width":(w+20)+'px',"height":(h+63)+'px'});
		$(".sciframe").css({"width":w+'px',"height":h+'px'});
	},
	colorSelect: function(){parent.dialog.iframe(1,'颜色选择器','?m=platform&a=dialog&do=color',0,1,400,230);},
	tab: function (n)
	{
		if(this.tabId==n) return false;
		$(".nav_info div").removeClass('info').addClass('info2');
		$(".nav_info div").eq(n-1).removeClass('info2').addClass('info');
		$("div #stab_"+this.tabId).fadeOut("fast", function(){$("div #stab_"+n).fadeIn();});
		this.tabId = n;
	},
	categoryTree: function(pid)
	{
		/** todo: 显示/隐藏 栏目树 **/
		var img = $("#cat_menu #img_"+pid).attr('src');
		$.browser.msie?img = img.replace(SITE_URL,'./'):'';
		if(img == './images/system/icon/63.gif'||img == './images/system/icon/61.gif')
		{
			var newImg = img == './images/system/icon/63.gif'?64:62;
			$("#cat_menu #img_"+pid).attr('src','./images/system/icon/'+newImg+'.gif');
			$('#cat_menu div').each(function(){
				if($(this).attr('pid')==pid){$(this).show();}
			});
		}
		else{this.hideCategoryChild(pid);}
	},
	hideCategoryChild: function(pid)
	{
		/** todo: 隐藏子节点 **/
		var img = $("#cat_menu #img_"+pid).attr('src');
		if(img == './images/system/icon/62.gif'||img == './images/system/icon/64.gif')
		{	
			var newImg = img == './images/system/icon/64.gif'?63:61;
			$("#cat_menu #img_"+pid).attr('src','./images/system/icon/'+newImg+'.gif');
			$('#cat_menu div').each(function(){
				if($(this).attr('pid')==pid)
				{
					var id = $(this).attr('id');
					id = id.replace(/(^cat_*)/g, "");
					$(this).hide();
					global.hideCategoryChild(id);
				}
			});
		}
	},
	showCategoryParent: function(catid)
	{
		/** todo: 显示所有上级节点 **/
		var pid = $("#cat_menu #cat_"+catid).attr('pid');
		if(pid==0)return false;
		//生成数组，将数组翻转
		$.each($.makeArray($('#cat_menu div')).reverse(),function(){
			//显示同级节点
			$(this).attr('pid')==pid && $(this).show();
			//将节点图标变更为展开
			var thisId = $(this).attr('id');
			thisId = thisId.replace(/(^cat_*)/g, "");
			if(thisId==pid)
			{
				var img = $("#cat_menu #img_"+thisId).attr('src');
				$.browser.msie?img = img.replace(SITE_URL,'./'):'';
				if(img == './images/system/icon/61.gif'||img == './images/system/icon/63.gif')
				{
					var newImg = img == './images/system/icon/63.gif'?64:62;
					$("#cat_menu #img_"+thisId).attr('src','./images/system/icon/'+newImg+'.gif');	
				}
				global.showCategoryParent(thisId);
			}
		});
	},
	thumbUpload: function(f){var frame = typeof f == 'undefined'?1:2;parent.dialog.iframe(frame,'缩略图上传','?m=platform&a=dialog&do=thumb&frame='+(frame-1),1,1,400,200);},
	getSpecial: function(){parent.dialog.iframe(1,'专题选择','?m=platform&a=dialog&do=special',1,1,600,350);},
	lineClick: function(n)
	{
		var flag = ($("#tr_"+n+" .checkbox").attr("checked")==true)?true:false;
		flag?$("#tr_"+n).removeClass("tr_selected"):$("#tr_"+n).addClass('tr_selected');
		flag?$("#tr_"+n+" .checkbox").removeAttr("checked"):$("#tr_"+n+" .checkbox").attr("checked",'true');
	}
}

var app = {
	deleteCategory: function(catid,model)
	{
		parent.dialog.iframe(1,'栏目删除','?m=document&a=category&do=deleteset&model='+model+'&catid='+catid,1,1,350,150);
	},
	categoryCheck: function()
	{
		var catName = $.trim($("#name").val());
		var catDir = $.trim($("#dir").val());
		if(catName == '' || catName.length>16)
		{
			parent.dialog.alert('栏目名不能为空，且长度在0~16个字符，请正确填写！');
			return false;
		}
		else if(catDir=='' || catDir.match(/^[A-Za-z0-9_-]{2,10}$/)==false)
		{
			parent.dialog.alert('栏目目录不能为空，且长度在0~10个字符的英文，请正确填写！');
			return false;
		}
		return true;
	},
	moveDocument: function(catid,dir,msg)
	{
		
	},
	emptyDocument: function()
	{
		
	},
	color: function(str){parent.window.frames[0].$("#color").val(str);parent.dialog.dialogClose(1);},
	special: function()
	{
		var special = '';
		$(".checkbox").each(function(){
			if( $(this).attr('checked') == true )
			{
				var sid = $(this).val();
				special += sid+' ';
			}
		});
		parent.window.frames[0].$("#special").val(special);
		parent.dialog.dialogClose(1);
	},
	articleEdit: function(aid,page){parent.$("#main").attr('src',SITE_URL+SCRIPT+'?m=article&a=edit&do=editarticle&id='+aid+'&page='+page);parent.dialog.dialogClose(1);},
	delPageConfirm: function(aid,page){parent.dialog.query('此操作不可恢复，是否确定删除？','app.delPage('+aid+','+page+')');},
	delPage: function(aid,page)
	{
		$("#dialog_iframe").attr('src',SITE_URL+SCRIPT+'?m=article&a=mag&do=delpage&id='+aid+'&page='+page);
		parent.window.frames[0].$("#tr_"+aid+' #pageno').text(parent.window.frames[0].$("#tr_"+aid+' #pageno').text()-1);
	},
	categoryArticleList: function(cid){parent.$("#main").attr('src',SITE_URL+SCRIPT+'?m=article&a=mag&do=list&type=cat&id='+cid);parent.dialog.dialogClose(1);},
	newArticle: function(cid){parent.$("#main").attr('src',SITE_URL+SCRIPT+'?m=article&a=new&do=newarticle&cat='+cid);parent.dialog.dialogClose(1);},
	articleCopy: function()
	{
		var ids = $("#ids").val();
		var cids = getChecked();
		if(cids=='')
		{
			parent.dialog.alert('请选择要复制到的文档分类！');
			return fasle;
		}
		var strCids = cids.join('_');
		parent.dialog.alert('正在复制中，请稍后。。。',1);
		$.ajax({
			url: SITE_URL+SCRIPT+"?m=article&a=mag&do=copy",
			data: {'ids':ids,'cids':strCids},
			error: function (xmlHttpRequest, error) {
				parent.$("#dialog_alert #msg").text('AJAX数据获取异常！');
			},
			success: function(rs)
			{
				parent.$("#dialog_alert #msg").text(rs?'成功复制文档！':'复制文档失败！');
				parent.main.location.reload();
			}
		});
	},
	articleMove: function()
	{
		var ids = $("#ids").val();
		var cid = getChecked();
		if(cid=='')
		{
			parent.dialog.alert('请选择要转移到的文档分类！');
			return fasle;
		}
		parent.dialog.alert('正在转移中，请稍后。。。',1);
		$.ajax({
			url: SITE_URL+SCRIPT+"?m=article&a=mag&do=move",
			data: {'ids':ids,'cid':cid},
			error: function (xmlHttpRequest, error) {
				parent.$("#dialog_alert #msg").text('AJAX数据获取异常！');
			},
			success: function(rs)
			{
				parent.$("#dialog_alert #msg").text(rs?'成功转移文档！':'转移文档失败！');
				parent.main.location.reload();
			}
		});
	},
	articleDel: function(ids)
	{
		parent.dialog.alert('正在删除中，请稍后。。。');
		$.ajax({
			url: SITE_URL+SCRIPT+"?m=article&a=mag&do=delarticle",
			data: {'ids':ids},
			error: function (xmlHttpRequest, error) {
				parent.$("#dialog_alert #msg").text('AJAX数据获取异常！');
			},
			success: function(rs)
			{
				parent.$("#dialog_alert #msg").text(rs?'成功删除文档！':'删除文档失败！');
				parent.main.location.reload();
			}
		});
	}
}

var autoSave = {
	msg: [' 秒后自动保存', '正在保存...', ' 已自动保存', '自动保存失败', '禁止自动保存', '于 ', '内容为空，跳过保存', 'AJAX数据获取发生异常', '内容无变化，跳过保存'],
	saveData: '',
	autoSaveTime: 120,
	autoSaveMode: 1,
	saveTime: 120,
	run: function ()
	{
		if(this.autoSaveMode==1)
		{
			this.saveTime = this.saveTime-1;
			if(this.saveTime >= 1)
			{
				$("#autosave #savemsg").text(this.saveTime+' '+this.msg[0]);
				window.setTimeout("autoSave.run()", 1000);
			}
			else{$("#autosave #savemsg").text(this.msg[1]);this.save();}
		}
	},
	start: function (){if(this.autoSaveMode==1)return false;else{this.autoSaveMode=1;this.run();}},
	suspend: function (){this.autoSaveMode=2;this.run();},
	disable: function (){$("#autosave #savemsg").text(this.msg[4]);this.autoSaveMode=2;this.saveTime=this.autoSaveTime;this.run();},
	save: function ()
	{
		this.autoSaveMode=2;
		this.saveTime=this.autoSaveTime;
		var datas = KE.util.getData('content');
		if(datas==''||datas=='<br />'||datas=='<p>&nbsp;</p>') {this.error(1);}
		else if(datas==this.saveData){this.error(4);}
		else
		{
			this.saveData = datas;
			$.ajax({
				url: SITE_URL+"editor.php?m=data&a=savedata",
				data: {'datas':datas},
				error: function (xmlHttpRequest, error) {
					autoSave.error(3);
				},
				success: function(rs)
				{
					if(rs.ok==1)
					{
						$("#autosave #savemsg").text(autoSave.msg[5]+rs.time+autoSave.msg[2]);
						autoSave.autoSaveMode=1;
						window.setTimeout("autoSave.run()", 3000);
					}
					else{this.error(2);}
				}
			});
		}
	},
	error: function(n)
	{
		var text;
		if(n==1) text = this.msg[6];
		else if(n==2) text = this.msg[3];
		else if(n==3) text = this.msg[7];
		else if(n==4) text = this.msg[8];
		$("#autosave #savemsg").text(text);
		this.autoSaveMode=1;
		window.setTimeout("autoSave.run()", 3000);
	},
	recover: function()
	{
		$.ajax({
			url: SITE_URL+"editor.php?m=data&a=getlist",
			error: function (xmlHttpRequest, error) {
				$("#autosave #s_recover").show();
			},
			success: function(rs)
			{
				$("#autosave .recover").html('');
				var no = rs.length;
				if( no != 0 ){for(i=0; i<no; i++){$("#autosave .recover").append("<li><a href='javascript:void(0)' onclick='autoSave.insertData("+rs[i].id+")'>"+rs[i].time+"</a></li>");}}
				$("#autosave #s_recover").show();
			}
		});
	},
	insertData:function(n)
	{
		$.ajax({
			url: SITE_URL+"editor.php?m=data&a=getdata",
			data: {'id':n},
			error: function (xmlHttpRequest, error) {
				$("#autosave #s_recover").hide();
			},
			success: function(rs)
			{
				autoSave.clearEditor('content');autoSave.insertHtml('content', rs.data);
				$("#autosave #s_recover").hide();
			}
		});
	},
	clearEditor: function (id) {
		KE.g[id].iframeDoc.open();
		KE.g[id].iframeDoc.write(KE.util.getFullHtml(id));
		KE.g[id].iframeDoc.close();
		KE.g[id].newTextarea.value = '';
	},
	insertHtml: function (id, html) {
		KE.util.focus(id);
		KE.util.selection(id);
		KE.util.insertHtml(id, html);
	}
}